package icu.shaoyayu.common.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.shaoyayu.common.utll.ReturnUtil;
import icu.shaoyayu.common.utll.exception.CustomExceptionType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author shaoyayu
 * readme ：
 * 访问接口权限不足时
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(new ObjectMapper().writeValueAsString(ReturnUtil.error(CustomExceptionType.AUTHORITY_AUTHENTICATION_ERROR)));
        out.flush();
        out.close();
    }
}
